(function() {
	'use strict';
	require(['box', 'navigation', 'dynamicTable', 'bootstrapTable', 'bootstrapTableZh', 'bootstrap', 'confirm'], function(box, navigation, dynamicTable) {
		
		if(typeof jQuery === 'undefined') {	//检测jquery依赖项
			throw new Error('jquery依赖项未能加载');
		}
		
		if(typeof $.fn.bootstrapTable === 'undefined') {	//检测bootstrapTable依赖项
			throw new Error('bootstrapTable依赖项未能加载');
		}
		
		var $table = $('#value_retrieve'),	//jquery包装table对象，使其能够调用扩展后jquery的方法
    	selections = [];
		$('#selectedProvince').data('table', $table);
		//初始化表格
		function initTable() {	//加载内容
	        $table.bootstrapTable({
				width: '90%',
	            columns: [
	      			{width: '30%', field: 'targetNameOfImplphase', title: '实施期目标', align: 'center'},
	      			{width: '30%', field: 'projectName', title: '工程名称', align: 'center'},
	      			{width: '30%', field: 'targetAttributeName', title: '项目名称', align: 'center'},
	      			{width: '10%', field: 'crud', title: '操作', align: 'center', events: roleEvents, formatter: operateFormatter}
	      		]
	        });
	        setTimeout(function () {
	            $table.bootstrapTable('resetView');
	        }, 200);
	        
	        $table.on('expand-row.bs.table', function (e, index, row, $detail) {
	        	var detail = detailFormatter(index, row);
	        	$detail.html(detail);
	        });
	        $table.on('all.bs.table', function (e, name, args) {
	            console.log(name, args);
	        });
	    }
		
		$('#updateReferenceValue').unbind('click').bind('click', updateReferenceValue);
		
		function updateReferenceValue(evt) {
			$('#updateReferenceValue').find('.save').attr('disable', true).find('.commit').attr('disable', true);
			var target = evt.target, cls = $(target).attr('class'),
			commit = "commit", save = "save", index = -1, statu = "", indexDatas = {};
			if(cls.indexOf(save) > index) {
				//保存
				indexDatas["statu"] = 0;
			} else if(cls.indexOf(commit) > index){
				//提交
				indexDatas["statu"] = 1;
			} else {
				$('#updateReferenceValue').find('.save').attr('disable', false).find('.commit').attr('disable', false);
				return false;
			}
			dynamicTable.getIndexes('reportReferenceValue_update', indexDatas);
			$.ajax({
				url: "index/updateIndexs",
				type: 'post',
				dataType: 'json',
				data: JSON.stringify(indexDatas),
				contentType : 'application/json;charset=utf-8',
				success: function(data) {
					if(data && data.success) {
						$.alert({title:'提示', content:'参考值设置成功!'});
						$.ajax({
							url: 'targetsOfImplPhase/retrieveTargetsPhaseByDivisionCodeAndOrgId.service',
							type: 'post',
							data: {
								divisionCode: $('#selectedProvince').data('selectedProvince').code, 
								oid: orange.getAppContext('ORGANIZATION').oid
							},
							success: function(data) {
								var rowData = null;
								if(data && data.success) {
								     rowData = data.data;
								     if(rowData.length == 0) {
								    	 $.alert({title: '提示', content: item.name + '下没有该司局相关的实施期目标'});
								    	 $table.bootstrapTable('load', rowData);
								     } else {
								    	 $table.bootstrapTable('load', rowData);
								     }
								}else if(data && data.success == false) {
									$.alert({title:'提示', content: data.errorMsg});
								}						
							}
						});
						modal.modal('hide');
        			} else {
        				$.alert({title:'提示', content: data.errorMsg});
        			}
				},
				complete: function() {
					$('#updateReferenceValue').find('.save').attr('disable', false).find('.commit').attr('disable', false);
				},
				error: function() {}
			});
		}
		
		function getIdSelections() {
	        return $.map($table.bootstrapTable('getSelections'), function (row) {
	            return row.id;
	        });
	    }
	    function responseHandler(res) {
	        $.each(res.rows, function (i, row) {
	            row.state = $.inArray(row.id, selections) !== -1;
	        });
	        return res;
	    }
	    function detailFormatter(index, row) {
	        var html = [];
	        $.each(row, function (key, value) {
	            html.push('<p><b>' + key + ':</b> ' + value + '</p>');
	        });
	        return html.join('');
	    }
	    
	    function operateFormatter(value, row, index) {
	        return [
				'<a class="edit" href="javascript:void(0)" title="设置指标参考值">',
				'<i class="glyphicon glyphicon-edit"></i>',
				'</a>  ',
	        ].join('');
	    }
	    
	    window.roleEvents = {
	        //修改指标值
	        'click .edit': function (e, value, row, index) {
		    	var updateUrl = "system/getPage.service?path=manage/otherDepartment/reportReferenceValueUpdate",
	        	_target = 'update_modal_body', _selector= "#reportReferenceValue_update";
	        	orange.loadPage({url: updateUrl, target: _target, selector: _selector, success: function(response){
	        		$('#targetOfImplPhase').find('input[name="projectName"]').val(row.projectName);
	        		$('#targetOfImplPhase').find('input[name="targetAttributeName"]').val(row.targetAttributeName);
	        		setValueToReportReference(row);
	    			
	    			$('#updateModal').modal({backdrop: "static"});
	    			/*btn_sure.unbind('click').bind('click', function() {
						var indexDatas = {};
	    				btn_sure.attr('disable', true);
	    				dynamicTable.getIndexes('reportReferenceValue_update', indexDatas);
	    				$.ajax({
	    					url: "index/updateIndexs",
	    					type: 'post',
	    					dataType: 'json',
	    					data: JSON.stringify(indexDatas),
	    					contentType : 'application/json;charset=utf-8',
	    					success: function(data) {
	    						if(data && data.success) {
	    							$.alert({title:'提示', content:'参考值设置成功!'});
	    							$.ajax({
	        							url: 'targetsOfImplPhase/retrieveTargetsPhaseByDivisionCodeAndOrgId.service',
	        							type: 'post',
	        							data: {
	        								divisionCode: $('#selectedProvince').data('selectedProvince').code, 
	        								oid: orange.getAppContext('ORGANIZATION').oid
	        							},
	        							success: function(data) {
	        								var rowData = null;
	        								if(data && data.success) {
	        								     rowData = data.data;
	        								     if(rowData.length == 0) {
	        								    	 $.alert({title: '提示', content: item.name + '下没有该司局相关的实施期目标'});
	        								    	 $table.bootstrapTable('load', rowData);
	        								     } else {
	        								    	 $table.bootstrapTable('load', rowData);
	        								     }
	        								}else if(data && data.success == false) {
	        									$.alert({title:'提示', content: data.errorMsg});
	        								}						
	        							}
	        						});
	    							modal.modal('hide');
			        			} else {
			        				$.alert({title:'提示', content:'参考值设置失败，网络异常.....'});
			        			}
	    					},
	    					complete: function() {
	    						btn_sure.attr("disabled", false);
	    					},
	    					error: function() {}
	    				});
	     				
	    			});*/
	    			
	    			//给实施期目标赋值
	    		    function setValueToReportReference(objData) {
	    		    	//分解实体类
	    				var targetNameOfImplphase = objData.targetNameOfImplphase? objData.targetNameOfImplphase : ""; //实施期目标名称
	    				var targetNameOfImplphaseId = objData.id? objData.id: "";
	    				var projectId = objData.projectId? objData.projectId: "";
	    				var targetAttribute =objData.targetAttribute? objData.targetAttribute: "";		//"目标属性"
	    				var annualTargetDatalist = objData.annualTargetDatalist?objData.annualTargetDatalist: [];	//年度目标数组
	    				var indexdata = objData.indexEntityList? objData.indexEntityList: [];	//指标，包括：实施期、年度
	    		    	
	    				//实施期目标只有一个，直接赋值
	    				$('#referenceValueOfTarget').val(targetNameOfImplphase);
	    				$('#update_project').val(projectId).trigger('change');
	    				$('#update_attribute').val(targetAttribute).trigger('change');
	    		    	
	    		    	//给年度目标赋值
	    				var aunnalTargetDivs = buildAunnalTargetDivs(annualTargetDatalist);
	    		    	$('#annualTargetlist').append(aunnalTargetDivs);
	    		    	
	    		    	//给指标赋值
	    		    	handleIndex(indexdata);
	    		    	
	    				//构造年度目标
	    				function buildAunnalTargetDivs(annualTargetDatalist) {
	    					var len = annualTargetDatalist? annualTargetDatalist.length : 0, i = 0, resultStr = "";
	    					for(i=0; i<len; i++) {
	    						resultStr += '<div class="aunnalTargetBox" data-index="1">'
	    						+ '<label class="lr-4 ">目标' + (i+1) + ':</label>'
	    						+ '<input class= "fill-1" name="annualTargets" value=' + $.trim(annualTargetDatalist[i]['annualTargets']) + '></input>'
	    						+ '</div>' + '\n';
	    					}
	    					
	    					return resultStr;
	    				}
	    				
	    				//构造指标
	    				function handleIndex(indexData) {
	    					//注意需要id，更新时，需要id直接更新
	    					var i = 0, len =indexData? indexData.length : 0, tempObj = null,
    							id = "", firstIndex = "", secondIndex="", thirdIndex="",
    							indexValue = "", targetType = "", referValue = "",
    							outerdivClsIndex = "", //需要添加一个空格
    							innerDivCls = "", //需要加一个空格
    							filledConstant = "filled", notfilledConstant = "notFilled",
    							outBox = {}, innerBox={}, innerBoxNotFilled = {},
    							$innerBoxNotFilled = {}, innerBoxNotFilledLen = 0, newBox = "";
	    					
	    					for(i = 0; i<len; i++) {
	    						tempObj = indexData[i];
	    						id = tempObj['id'];
	    						firstIndex = tempObj['firstIndex'];
	    						secondIndex = tempObj['secondIndex'];
	    						thirdIndex = tempObj['thirdIndex'];
	    						indexValue = tempObj['indexValue'];
	    						targetType = tempObj['targetType'];
	    						referValue = tempObj['referValue'];
	    						
	    						outerdivClsIndex = targetType + "_" + firstIndex + '_' + secondIndex;
	    						innerDivCls = 'ac_box' + notfilledConstant;
	    						
	    						outBox= $('.targetBox.' + outerdivClsIndex);
	    						innerBox = outBox.children();
	    						
	    						innerBoxNotFilled = outBox.find('.ac_box.' + notfilledConstant);
	    						$innerBoxNotFilled = $(innerBoxNotFilled);
	    						innerBoxNotFilledLen = $innerBoxNotFilled.length;
	    							
	    						if(innerBoxNotFilledLen == 0) {
	    							//构造div
	    							newBox = '<div class="ac_box filled" data-index="' + parseInt(innerBoxNotFilledLen + 1) + '">'
	    									+'<input name="id" type="hidden" value="' + id + '"></input>'
	    					       		   	+ '<label class="lr-4 span-add">指标' + parseInt(innerBoxNotFilledLen + 1) + ':</label>'
	    					       		   	+ '<input class= "fill-4-1" name="' + thirdIndex + '"></input>'
	    					       		   	+ '<label class="lr-4 span-add">参考值</label>'
	    					       		   	+ '<input class= "fill-4-1" name="referValue"></input>'
	    					       		   	+ '</div>';
	    							//添加一个新的div
	    							outBox.append(newBox);
	    						} else {
	    							//有notFilled的div，那就直接插入值
	    							$innerBoxNotFilled.find('input[name="thirdIndex"]').val(thirdIndex);
	    							$innerBoxNotFilled.find('input[name="id"]').val(id);
	    							$innerBoxNotFilled.find('input[name="referValue"]').val(referValue);
	    							$innerBoxNotFilled.removeClass(notfilledConstant).addClass(filledConstant);
	    						} 
	    					}
	    				}
	    		    }
	        	}});
	        }
	    };
	    
	    
    	var opts = {
			type: 'TITLE',
			position: 'SUBTOPLARGE',
			selected: '',
			data: getDefaultProvince(),
			field: {title: 'name'},
			onSelect: function(item) {
				$.ajax({
					url: 'targetsOfImplPhase/retrieveTargetsPhaseByDivisionCodeAndOrgId.service',
					type: 'post',
					data: {divisionCode: item.code, oid: orange.getAppContext('ORGANIZATION').oid},
					success: function(data) {
						var rowData = null;
						if(data && data.success) {
						     rowData = data.data;
						     if(rowData.length == 0) {
						    	 $.alert({title: '提示', content: item.name + '下没有该司局相关的实施期目标'});
						    	 $table.bootstrapTable('load', rowData);
						     } else {
						    	 $table.bootstrapTable('load', rowData);
						     }
						}else if(data && data.success == false) {
							$.alert({title:'提示', content: data.errorMsg});
						}						
					}
				});
				$('#selectedProvince').data('selectedProvince', item);
			},
			onLoaded: function() {
				console.log('navSubTop组件创建完成');
			}
		};
	    
	    function getDefaultProvince() {
	    	return [{code: '110000', name: '北京市'},
			    	{code: '120000', name: '天津市'},
			    	{code: '130000', name: '河北省'},
			    	{code: '140000', name: '山西省'},
			    	{code: '150000', name: '内蒙古自治区'},
			    	{code: '210000', name: '辽宁省'},
			    	{code: '220000', name: '吉林省'},
			    	{code: '230000', name: '黑龙江省'},
			    	{code: '310000', name: '上海市'},
			    	{code: '320000', name: '江苏省'},
			    	{code: '330000', name: '浙江省'},
			    	{code: '340000', name: '安徽省'},
			    	{code: '350000', name: '福建省'},
			    	{code: '360000', name: '江西省'},
			    	{code: '370000', name: '山东省'},
			    	{code: '410000', name: '河南省'},
			    	{code: '420000', name: '湖北省'},
			    	{code: '430000', name: '湖南省'},
			    	{code: '440000', name: '广东省'},
			    	{code: '450000', name: '广西壮族自治区'},
			    	{code: '460000', name: '海南省'},
			    	{code: '500000', name: '重庆市'},
			    	{code: '510000', name: '四川省'},
			    	{code: '520000', name: '贵州省'},
			    	{code: '530000', name: '云南省'},
			    	{code: '540000', name: '西藏自治区藏'},
			    	{code: '610000', name: '陕西省'},
			    	{code: '620000', name: '甘肃省'},
			    	{code: '630000', name: '青海省'},
			    	{code: '640000', name: '宁夏回族自治区'},
			    	{code: '650000', name: '新疆维吾尔自治区'},
			    	{code: '660000', name: '新疆生产建设兵团'}];
	    }
	    
	    initTable();
	    navigation.create('#selectedProvince', opts);
		
	});
})();